package org.operator.receive;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ReceiveSource {

	private ResultSet res;
	
	private static ReceiveSource source;
	
	
	private ReceiveSource(ResultSet res)
	{
		this.res = res;
	}
	
	/**
	 * @param res
	 * @return
	 */
	public static ReceiveSource getInstance(ResultSet res) 
	{
		if (source == null) {
			source = new ReceiveSource(res);
		} else {
			source.setRes(res);
		}
		
		return source;
	}
	
	
	public ResultSet getRes() {
		return res;
	}


	public void setRes(ResultSet res) {
		this.res = res;
	}

	/**
	 * 接收list
	 * @return
	 */
	public List<Map<String, Object>> handleResultSetToMapList() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			ResultSetMetaData md = this.res.getMetaData();
			int columnCount = md.getColumnCount();
			while (this.res.next()) {
				Map<String, Object> rowData = new HashMap<String, Object>();
				for (int i = 1; i <= columnCount; i++) {
					rowData.put(md.getColumnName(i), this.res.getObject(i));
				}
				list.add(rowData);
			}
			return list;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * 接收map
	 * @return
	 */
	public Map<String, Object> handleResultSetToMap() {
		// TODO Auto-generated method stub
		Map<String, Object> rowData = new HashMap<String, Object>();
		try {
			ResultSetMetaData md = this.res.getMetaData();
			int columnCount = md.getColumnCount();
			while (this.res.next()) {
				for (int i = 1; i <= columnCount; i++) {
					rowData.put(md.getColumnName(i), this.res.getObject(i));
				}
			}
			return rowData;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

}
